package com.eastedu.superise.handler.question;

import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.eastedu.client.warehouse.JyeooResourceSearchClient;
import com.eastedu.client.warehouse.model.KnowledgeInfoDTO;
import com.eastedu.client.warehouse.model.KnowledgeMatchVO;
import com.eastedu.repository.question.mapper.QuestionAssociationMapper;
import com.eastedu.repository.question.mapper.QuestionBasicInfoMapper;
import com.eastedu.repository.question.po.QuestionAssociationPO;
import com.eastedu.repository.question.po.QuestionBasicInfoPO;
import com.eastedu.superise.handler.AbstractHistoricalDataHandler;
import com.eastedu.util.QuestionUtil;
import com.eastedu.utils.PrimaryKeyGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 袁松明
 */
@Slf4j
@Service
@DS("question")
public class QuestionInsertKnowledgeHistoricalDataHandler extends AbstractHistoricalDataHandler<QuestionBasicInfoPO> {
    private final JyeooResourceSearchClient jyeooResourceSearchClient;
    private final QuestionAssociationMapper questionAssociationMapper;
    private final QuestionBasicInfoMapper questionBasicInfoMapper;

    public QuestionInsertKnowledgeHistoricalDataHandler(JyeooResourceSearchClient jyeooResourceSearchClient,
                                                        QuestionAssociationMapper questionAssociationMapper,
                                                        QuestionBasicInfoMapper questionBasicInfoMapper) {
        this.jyeooResourceSearchClient = jyeooResourceSearchClient;
        this.questionAssociationMapper = questionAssociationMapper;
        this.questionBasicInfoMapper = questionBasicInfoMapper;
    }

    @Override
    protected String getSql() {
        /*
            故事ID：89097
            只处理闻到库
            将题库内小学数学；初中、高中数学、物理、化学、生物、政治、历史、地理学科内的无知识点试题进行批量智能标注处理
            'XX'    'SX'
            'CZ'    'SX','WL','HX','SW','ZZ','LS','DL'
            'GZ'    'WL','HX','SW','ZZ','LS','DL'
         */
        return "SELECT " +
                "  DISTINCT question.* " +
                "FROM\n" +
                "t_question_basic_info AS question\n" +
                "    LEFT JOIN t_question_association AS question_knowledge ON question.id = question_knowledge.question_id AND question_knowledge.type = 1\n" +
                "    left join t_question_source sour on sour.question_id = question.id\n" +
                "WHERE\n" +
                "question_knowledge.id IS NULL AND\n" +
                "question.audit_state = 2 and\n" +
                "question.study_period IN ('GZ')\n" +
                "AND question.`subject` IN ('WL','HX','SW','ZZ','LS','DL')\n" +
                "    and sour.organization in(\n" +
                "'1b64f67b-9edc-4f7a-909c-843ffdc7acd4',\n" +
                "'c4b13225-4f0e-4c4e-9699-dd5d33739816',\n" +
                "'5226c2dc-724a-4467-9b2d-19acf7a9b039',\n" +
                "'df1ca3f0-477e-42c5-9d16-b6bff7007bbe',\n" +
                "'20ea8f5e-ed31-4638-8b75-f1d0dca8817e',\n" +
                "'dbca0108-359d-4eff-8e9d-e17f41391155',\n" +
                "'8c669c4b-a245-48da-ab03-4743f3c31838'\n" +
                ")" +
                "ORDER BY question.id";
    }

    @Override
    public void callback(QuestionBasicInfoPO questionBasicInfoPo) throws SQLException {
        String questionContentString = QuestionUtil.extractContent(questionBasicInfoPo.getQuestion());
        if (Objects.isNull(questionContentString)) {
            log.warn("解析试题题干失败，跳过知识点填充，试题ID：{}", questionBasicInfoPo.getId());
            return;
        }
        List<KnowledgeInfoDTO> knowledge = this.getKnowledge(questionContentString,
                questionBasicInfoPo.getStudyPeriod(), questionBasicInfoPo.getSubject());
        if (CollectionUtils.isEmpty(knowledge)) {
            log.warn("解析试题知识点失败，无匹配知识点，试题ID：{}", questionBasicInfoPo.getId());
            return;
        }
        List<QuestionAssociationPO> questionAssociationPoList
                = this.createQuestionAssociationPoList(questionBasicInfoPo.getId(), knowledge,
                questionBasicInfoPo.getStudyPeriod(), questionBasicInfoPo.getSubject());
        questionAssociationMapper.deleteAllByQuestionId(questionBasicInfoPo.getId());
        questionAssociationPoList.forEach(questionAssociationMapper::insert);
        // 关联表type=1，主表上type=0
        questionAssociationPoList.forEach(item -> {
            item.setType(0);
        });
        String knowledgeString = JSON.toJSONString(questionAssociationPoList);
        questionBasicInfoMapper.updateKnowledgeById(questionBasicInfoPo.getId(), knowledgeString);
    }


    private List<KnowledgeInfoDTO> getKnowledge(String content, String section, String subject) {
        KnowledgeMatchVO knowledgeMatchVo = new KnowledgeMatchVO();
        knowledgeMatchVo.setContent(content);
        knowledgeMatchVo.setSection(section);
        knowledgeMatchVo.setSubject(subject);
        try {
            return jyeooResourceSearchClient.match(knowledgeMatchVo);
        } catch (Exception e) {
            log.error("获取知识点失败：{}", e.getMessage(), e);
            return new ArrayList<>();
        }
    }

    private List<QuestionAssociationPO> createQuestionAssociationPoList(Long questionId,
                                                                        List<KnowledgeInfoDTO> knowledge,
                                                                        String section, String subject) {
        if (CollectionUtils.isEmpty(knowledge)) {
            return new ArrayList<>();
        }
        return knowledge.stream().filter(Objects::nonNull).map(knowledgeInfo
                        -> this.createQuestionAssociationPo(questionId, knowledgeInfo, section, subject))
                .collect(Collectors.toList());
    }

    private QuestionAssociationPO createQuestionAssociationPo(Long questionId, KnowledgeInfoDTO knowledge,
                                                              String section, String subject) {
        Long associationId = PrimaryKeyGenerator.generateKey();
        QuestionAssociationPO questionAssociationPo = new QuestionAssociationPO();
        questionAssociationPo.setAssociationId(knowledge.getNodeId());
        questionAssociationPo.setAssociationRootId(section + "_" + subject);
        questionAssociationPo.setQuestionId(questionId);
        questionAssociationPo.setType(1);
        questionAssociationPo.setId(associationId);
        questionAssociationPo.setCreateTime(Instant.now().toEpochMilli());
        questionAssociationPo.setUpdateTime(Instant.now().toEpochMilli());
        return questionAssociationPo;
    }
}
